package com.ff.kvm.team.service.impl;

import com.ff.kvm.common.dv.es.GiftBoxESDV;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.ConvertUtil;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.util.ResponseUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.team.common.TeamGiftUserDV;
import com.ff.kvm.team.es.entity.GiftBoxES;
import com.ff.kvm.team.es.entity.UserES;
import com.ff.kvm.team.es.repository.ESGiftBoxRepository;
import com.ff.kvm.team.es.util.ESUtil;
import com.ff.kvm.team.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class GiftBoxServiceImpl implements GiftBoxService {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private ESGiftBoxRepository giftBoxRepository;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private SysCodeService sysCodeService;


    @Override
    public Response<Boolean> addGiftBox(GiftBoxESDV giftBoxESDV) {
        giftBoxRepository.save(ConvertUtil.convert(giftBoxESDV,GiftBoxES.class));
        return ResponseUtil.success();
    }

    @Override
    public void exeGiftBox() {
        Date start = MyUtil.parseDate(redisService.getCache(Constants.TEAM_LAST_GIFT_BOX_SETTLE_TIME));
        Date end = new Date();

//        long day = MyUtil.betweenDay(start,end);
//        log.info("距离上一次礼包团队分红天数...",day);
//        if(day < Integer.valueOf(redisService.getCache(Constants.TEAM_GIFT_BOX_SETTLE_DAY))){
//            return;
//        }
        log.info("执行礼包团队分红...start");

        int maxFloor = userService.getMaxFloor();
        String[] cf = userService.getGiftBoxTeamCF();

        //存放绩效
        Map<Integer, Double> totalMap = new HashMap<>();
        for(int i = maxFloor;i>0;i--){
            List<UserES> userList = userService.findUserESByFloor(i);
            clbBonus(totalMap,userList,start,end,cf);
        }

        //记录上这次分红时间，为下次开始时间
        redisService.putCache(Constants.TEAM_LAST_GIFT_BOX_SETTLE_TIME,MyUtil.formatDateYMDhms(end));
        sysCodeService.updateSysCode(Constants.TEAM_LAST_GIFT_BOX_SETTLE_TIME,MyUtil.formatDateYMDhms(end));
        log.info("执行礼包团队分红...end");
    }

    @Transactional
    public void clbBonus(Map<Integer, Double> totalMap, List<UserES> userList, Date start, Date end,String[] cf) {
        for(UserES userES : userList){
            if(userES.getUpUserId() == 0 ){
                continue;
            }
            UserES upUser = userService.findUserESById(userES.getUpUserId());
            List<GiftBoxES> orderList = findGiftBoxESByUserId(userES.getUserId(),start,end);
            double total = sumTotal(orderList);
            if(totalMap.containsKey(userES.getUserId())){
                total = total + totalMap.get(userES.getUserId());
            }
            if(total == 0){
                continue;
            }


            //上级<=下级不返利
            if(upUser.getTeamGiftLv() <= userES.getTeamGiftLv()){
                continue;
            }
            if(totalMap.containsKey(userES.getUpUserId())){
                totalMap.put(userES.getUpUserId(),totalMap.get(userES.getUpUserId()) + total);
            }else{
                totalMap.put(userES.getUpUserId(),total);
            }
            double point = 0;
            if(userES.getTeamGiftLv() != 0){
                point = Double.valueOf(cf[userES.getTeamGiftLv()-1].split("-")[3]);
            }
            double upPoint = Double.valueOf(cf[upUser.getTeamGiftLv()-1].split("-")[3]);

            double md = MyUtil.float2(total*(upPoint - point));
            accountService.giftBonus(upUser.getUserId(),upUser.getTeamGiftLv(),upPoint,userES.getUserId(),userES.getTeamGiftLv(),point,md,total);

            if(totalMap.containsKey(userES.getUserId())){
                totalMap.remove(userES.getUserId());
            }

        }

    }

    private double sumTotal(List<GiftBoxES> list) {
        double total = 0;
        for (GiftBoxES giftBoxES : list){
            total += giftBoxES.getTotal();
        }
        return total;
    }

    private List<GiftBoxES> findGiftBoxESByUserId(int userId,Date start, Date end) {

        return giftBoxRepository.search(ESUtil.getSearchQuery(userId,start,end)).getContent();
    }


    @Override
    public Response<Boolean> executeGiftBox() {
        new Runnable() {
            @Override
            public void run() {
                exeGiftBox();
            }
        };
        return ResponseUtil.success();
    }
}
